package com.dd.ent.car.common.player;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.media.audiofx.AudioEffect;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.dd.ent.car.R;
import com.dd.ent.car.common.util.NetworkHelper;
import com.pp.ent.base.log.MLog;

/**
 * Author:LiuJianSheng
 * Date:2016/6/1
 * 系统播放器的一个封装，包含播放操作界面以及错误处理
 * _开头的方法如_start()，是对系统start()方法的封装，包含自定义的播放状态处理
 */
public class ThunderMediaPlayer {
    public static final String TAG = "liu.js.media";

    public static final int TYPE_AUTO_PLAY = 1;
    public static final int TYPE_SHORT_VIDEO_FEED = 2;
    public static final int TYPE_SHORT_VIDEO_DETAIL = 3;

    private int mPlayerId = PlayerIdGenerator.generatorPlayerId();
    private String mTag = "Player" + mPlayerId;
    private long mPlaySessionId = -1;
    private Context mContext;
    private AsyncMediaPlayer mMediaPlayer;
    private View mContainer;

    //    private TextureView mTextureView;
    private SurfaceView mSurfaceView;
    private PlayInfo mPlayInfo;
    private int mScreenWidth;
    private int mScreenHeight;
    private int mVideoWidth;
    private int mVideoHeight;

    //全屏
    private boolean isFullScreenMode;//是否是全屏模式
    private boolean isScreenLandscape;//当前是否横屏
    private MediaPlayerFullScreenListener mediaPlayerFullScreenListener;
    private ViewGroup mPrevParent;//之前的装载播放器的ViewGroup，用于全屏和退出全屏
    private ViewGroup.LayoutParams mPrevParams;
    private boolean shouldDetachOnFullScreenMode = true;//全屏模式时，是否需要从当前界面上remove掉，重新add到DecodeView上
    private long mFullScreenChangeTime;//全屏切换的时间，全屏切换后的一秒内定为全屏切换中状态，用来规避由于全屏切换，导致列表滚动，进而导致视频播放异常停止问题

    private MediaPlayerControllerView mControllerView;//控制界面
    private MediaPlayerErrorView mErrorView;//错误界面
    private MediaPlayerCompletionView mCompletionView;//播放完成界面
    private MediaPlayerGestureView mGestureView;//音量、进度操作页面

    private MediaPlayer.OnCompletionListener onCompletionListener;
    private boolean isPausedByUser;//是否由用户手动暂停
    private long mSetDataSourceTime;//设置数据源的时间，用来统计加载时长
    private boolean hasLimitDownloadSpeed;//是否有对下载限过速

    private OrientationEventListener mOrientationListener;
    private boolean mIsOrientationListenerEnabled;
    private static final int SCREEN_PORTRAIT = 1;
    private static final int SCREEN_LANDSCAPE = 2;
    private int mLastScreenOrientation = SCREEN_PORTRAIT;
    private boolean mClickLandscape = false;
    private boolean mClickPortrait = false;
    private boolean mPortraitVideoFullScreen = false;
    private boolean mAutoPlayEnable = false;
    private int mListPosition;//如果播放器处于列表中时，记录播放器在列表中的位置

    private int mViewType;

    private static boolean sShouldMute = true;
    private boolean mIsMute;

    public ThunderMediaPlayer(Context context) {
        this.mContext = context;
        mMediaPlayer = new AsyncMediaPlayer();
        initMediaPlayer(mMediaPlayer);

        initContainer();
        initSurfaceView(mContainer);
        initController(mContainer);
        initErrorView(mContainer);
        initCompletionView(mContainer);
        initGestureView(mContainer);
    }

    private void initContainer() {
        final View container = LayoutInflater.from(mContext).inflate(R.layout.media_player_layout, null);
        container.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (mScreenWidth != container.getWidth() || mScreenHeight != container.getHeight()) {
                    mScreenWidth = container.getWidth();
                    mScreenHeight = container.getHeight();
                    adjustScreen(mScreenWidth, mScreenHeight, mVideoWidth, mVideoHeight);
                }
            }
        });
        mContainer = container;
    }

    private void initMediaPlayer(final AsyncMediaPlayer mediaPlayer) {
        mediaPlayer.setPlayerListener(new PlayerListener() {
            @Override
            public void onBufferingUpdate(MediaPlayerWrapper mp, int percent) {
                //MLog.debug(TAG, "onBufferingUpdate--percent=" + percent + "|state=" + getState());
                mControllerView.OnBufferingUpdate(percent);
            }

            @Override
            public void onCompletion(MediaPlayerWrapper mp) {
                MLog.debug(TAG, "onCompletion--state=" + getState());
                onPlayEnd(false);
                //自动播放时直接切换不退出全屏
                if (!mAutoPlayEnable) {
                    outFullScreenMode();
                    enableOrientationListener(false);
                }
                if (onCompletionListener != null) {
                    onCompletionListener.onCompletion(mp.getMediaPlayer());
                }
            }

            @Override
            public boolean onError(MediaPlayerWrapper mp, int what, int extra) {
                MLog.debug(TAG, "onError--what=" + what + "|extra=" + extra + "|state=" + getState());
                onPlayEnd(true);
                return true;
            }

            @Override
            public boolean onInfo(MediaPlayerWrapper mp, int what, int extra) {
                MLog.debug(TAG, "onInfo--what=" + what + "|extra=" + extra + "|state=" + getState());
                return true;
            }

            @Override
            public void onVideoSizeChanged(MediaPlayerWrapper mp, int width, int height) {
                MLog.debug(TAG, "onVideoSizeChanged--width=" + width + "|height=" + height + "|state=" + getState());
                mVideoWidth = width;
                mVideoHeight = height;
                adjustScreen(mScreenWidth, mScreenHeight, width, height);
//                adjustScreenOrientationOnFullScreen();
            }

            @Override
            public void onPrepared(MediaPlayerWrapper mp) {
                MLog.debug(TAG, "onPrepared--state=" + getState());
                if (mPlayInfo != null) {
                    int duration = mediaPlayer.getDuration();
                    mGestureView.setMediaDuration(duration);
                    mPlayInfo.setDuration(duration);
                }
                start();
                if (mPlayInfo != null) {
                    VideoInfo videoInfo = mPlayInfo.getVideoInfo();
                    MLog.debug("liu.js.media", "onVideoPlayStart");
                    if (videoInfo.getPlayListener() != null) {
                        videoInfo.getPlayListener().onVideoPlayStart(videoInfo);
                    }
                    if (videoInfo.getStartPosition() > 0 && Math.abs(videoInfo.getStartPosition() - mPlayInfo.getDuration()) > 1000) {
                        safetySeekTo(videoInfo.getStartPosition());
                    }
                }
                reportPlayAllStart();
            }

            @Override
            public void onPlayPositionChange(int newPosition) {
                if (mPlayInfo != null) {
                    mPlayInfo.setCurrentPlayPosition(newPosition);
                }
                mControllerView.onPlayPositionChange(newPosition);
                if (mPlayInfo != null && !mPlayInfo.isHasInsertPlayRecord()) {
                    tryInsertShortVideoPlayRecord();
                }
            }

            @Override
            public void onSeekComplete(MediaPlayerWrapper mp) {

            }
        });
    }

    private void reportPlayAllStart() {
        if (mPlayInfo == null) {
            return;
        }
        VideoInfo videoInfo = mPlayInfo.getVideoInfo();
    }

    private void reportPlayEnd(String endType) {
        if (mPlayInfo == null) {
            return;
        }
        VideoInfo videoInfo = mPlayInfo.getVideoInfo();
        MLog.debug(TAG,"");
    }

    private void initSurfaceView(View rootView) {
        SurfaceView surfaceView = (SurfaceView) rootView.findViewById(R.id.surface_view);
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceView.setDrawingCacheEnabled(true);
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback2() {
            @Override
            public void surfaceRedrawNeeded(SurfaceHolder holder) {

            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                MLog.debug(TAG, "onSurfaceTextureAvailable--state=" + getState());
                if (mMediaPlayer == null) {
                    return;
                }
                mMediaPlayer.setDisplay(holder);
                if (mMediaPlayer.isPaused()) {
                    if (isPausedByUser) {
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT || Build.VERSION.SDK_INT > 22) {
                            safetySeekTo(getCurrentPosition());
                        }
                    } else {
                        start();
                    }
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                MLog.debug(TAG, "onSurfaceTextureDestroyed--state=" + getState());
                if (mMediaPlayer == null) {
                    return;
                }
                mMediaPlayer.setDisplay(null);
//                if (mMediaPlayer.isStarted()) {
//                    pause(false);
//                }
            }
        });
        mSurfaceView = surfaceView;
    }

//    private void initTextureView(View rootView) {
//        TextureView textureView = (TextureView) rootView.findViewById(R.id.texture_view);
//        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
//            @Override
//            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//                MLog.debug(TAG, "onSurfaceTextureAvailable--state=" + getState());
//                if (mMediaPlayer == null) {
//                    return;
//                }
//                mMediaPlayer.setSurfaceTexture(surface);
//                if (getState() == MediaPlayerState.PAUSED) {
//                    if(isPausedByUser){
//                        safetySeekTo(getCurrentPosition());
//                    }else{
//                        start();
//                    }
//                }
//            }
//
//            @Override
//            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
//                MLog.debug(TAG, "onSurfaceTextureSizeChanged--state=" + getState());
//            }
//
//            @Override
//            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
//                MLog.debug(TAG, "onSurfaceTextureDestroyed--state=" + getState());
//                if (mMediaPlayer == null) {
//                    return true;
//                }
//                mMediaPlayer.setSurfaceTexture(null);
//                if (getState() == MediaPlayerState.STARTED) {
//                    pause(false);
//                }
//                return true;
//            }
//
//            @Override
//            public void onSurfaceTextureUpdated(SurfaceTexture surface) {
////                MLog.debug(TAG, "onSurfaceTextureUpdated--state=" + getState());
//            }
//        });
//        mTextureView = textureView;
//    }

    private void initController(View rootView) {
        mControllerView = (MediaPlayerControllerView) rootView.findViewById(R.id.controller_view);
        mControllerView.setMediaPlayer(this);
        mMediaPlayer.addStateChangeListener(mControllerView);
    }

    private void initErrorView(View rootView) {
        mErrorView = (MediaPlayerErrorView) rootView.findViewById(R.id.error_view);
        mErrorView.setMediaPlayer(this);
        mMediaPlayer.addStateChangeListener(mErrorView);
    }

    private void initCompletionView(View rootView) {
        mCompletionView = (MediaPlayerCompletionView) rootView.findViewById(R.id.completion_view);
        mCompletionView.bindMediaPlayer(this);
        mMediaPlayer.addStateChangeListener(mCompletionView);
    }

    private void initGestureView(View rootView) {
        mGestureView = (MediaPlayerGestureView) rootView.findViewById(R.id.gesture_view);
        mGestureView.bindMediaPlayer(this);
        mMediaPlayer.addStateChangeListener(mGestureView);
    }

    private void initOrientationListener() {
        mOrientationListener = new OrientationEventListener(getActivity()) {
            @Override
            public void onOrientationChanged(int rotation) {
                if (rotation == OrientationEventListener.ORIENTATION_UNKNOWN)
                    return;
                if (rotation >= 0 && rotation <= 30 || rotation >= 330) { // Portrait
                    if (mClickLandscape) {
                        if (mLastScreenOrientation == SCREEN_LANDSCAPE) {
                            mClickLandscape = false;
                        }
                    } else {
                        if (isFullScreenMode()) {
                            if (mPortraitVideoFullScreen) {
                                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                            } else {
                                outFullScreenMode();
                            }
                        }
                    }
                    mLastScreenOrientation = SCREEN_PORTRAIT;
                } else if (rotation >= 60 && rotation <= 120 || rotation >= 240 && rotation <= 300) { // Landscape
                    if (mClickPortrait) {
                        if (mLastScreenOrientation == SCREEN_PORTRAIT) {
                            mClickPortrait = false;
                        }
                    } else {
                        if (mPortraitVideoFullScreen) {
                            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
                        } else {
                            enterFullScreenMode();
                        }
                    }
                    mLastScreenOrientation = SCREEN_LANDSCAPE;
                }
            }
        };
    }

    public void setOrientationListenerEnabled(boolean enabled) {
        MLog.debug(TAG, "setOrientationListenerEnabled(" + enabled + ")");
        mIsOrientationListenerEnabled = enabled;
        if (enabled) {
            if (mOrientationListener == null) {
                initOrientationListener();
            }
            if (isPlaying()) {
                enableOrientationListener(true);
            }
        } else {
            enableOrientationListener(false);
        }
    }

    private void enableOrientationListener(boolean enable) {
        if (mOrientationListener != null) {
            if (enable) {
                MLog.debug(TAG, "mOrientationListener.enable()");
                mOrientationListener.enable();
            } else {
                MLog.debug(TAG, "mOrientationListener.disable()");
                mOrientationListener.disable();
            }
        }
    }

    private void adjustScreen(int playerWidth, int playerHeight, int videoWidth, int videoHeight) {
        if (videoWidth == 0 || videoHeight == 0) return;

        float videoRatio = videoWidth / (float) videoHeight;
        float screenRatio = playerWidth / (float) playerHeight;

        int adjustWidth;
        int adjustHeight;

        if (videoRatio > screenRatio) {
            adjustWidth = playerWidth;
            adjustHeight = (int) (adjustWidth / videoRatio);
        } else {
            adjustHeight = playerHeight;
            adjustWidth = (int) (adjustHeight * videoRatio);
        }
        ViewGroup.LayoutParams params = mSurfaceView.getLayoutParams();
        if (params != null) {
            params.width = adjustWidth;
            params.height = adjustHeight;
            mSurfaceView.setLayoutParams(params);
        }
    }

    private void adjustScreenOrientationOnFullScreen() {
        if (!isFullScreenMode) {
            return;
        }
        boolean isVideoHorizontal = isVideoHorizontal() || !mClickLandscape;
        if (isScreenLandscape == isVideoHorizontal) {
            return;
        }
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        if (isVideoHorizontal) {
            isScreenLandscape = true;
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else {
            isScreenLandscape = false;
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    void release() {
        MediaPlayerState state =  getState();
        if (isPrepared() && (state == MediaPlayerState.STARTED || state == MediaPlayerState.PAUSED || state == MediaPlayerState.LOADING)) {
            onPlayEnd(false);
        }
        resetListenersAndParams();
        removeSelfContainer();
        mMediaPlayer.release();
        enableOrientationListener(false);
        outFullScreenMode();
//        mTextureView.setKeepScreenOn(false);
    }

    public void reset() {
        MLog.debug(TAG, "reset--");
        mMediaPlayer.reset();
//        mTextureView.setKeepScreenOn(false);
    }

    private void onPlayEnd(boolean isError) {
        tryInsertShortVideoPlayRecord();
        unLimitDownloadSpeed();
        if (mPlayInfo != null) {
            VideoInfo videoInfo = mPlayInfo.getVideoInfo();
            if (videoInfo.getPlayListener() != null) {
                videoInfo.getPlayListener().onVideoPlayEnd(videoInfo);
            }
        }
    }

    private void unLimitDownloadSpeed() {
        MLog.debug("SpeedLimit", " == unLimitDownloadSpeed ");
        //SpeedLimitHelper.instance().stopLimitDownloadSpeed();
    }

    public void play(final VideoInfo videoInfo) {
        if (videoInfo == null) {
            return;
        }
        MLog.debug(TAG, "play--state=" + getState() + "|movieId=" + videoInfo.getMovieId() + "|title=" + videoInfo.getTitle());
        if (mMediaPlayer == null) {
            return;
        }
        mControllerView.setPoster(videoInfo.getPoster());
        if (TextUtils.isEmpty(videoInfo.getSourceUrl())) {
            return;
        }
        final PlayInfo prevPlayInfo = mPlayInfo;
        mPlayInfo = new PlayInfo(videoInfo);
        boolean isCanPlay = true;
        if (NetworkHelper.isActiveNetworkMobile(mContext)) {
            String movieId = videoInfo == null ? "" : videoInfo.getMovieId();
            isCanPlay = MediaPlayerManager.getInstance().checkCanPlayAndPromptOnMobileNetwork(movieId, mContext, new MediaPlayerUtils.OnCheckNetworkDialogListener() {
                @Override
                public void onLeftBtnClick() {
                    reset();
                }

                @Override
                public void onRightBtnClick() {
                    doPlay(videoInfo, prevPlayInfo);
                }

                @Override
                public void onBackKeyDown() {

                }
            });
        }
        if (isCanPlay) {
            doPlay(videoInfo, prevPlayInfo);
        }
    }

    private void doPlay(VideoInfo videoInfo, PlayInfo prevPlayInfo) {
        limitDownloadSpeed();
        String movieId = videoInfo.getMovieId();
        if (prevPlayInfo != null && movieId.equals(prevPlayInfo.getVideoInfo().getMovieId())) {//播放的视频与上一次播放的视频相同
            if (isPrepared()) {
                MediaPlayerState state = getState();
                if (state == MediaPlayerState.PAUSED && isPausedByUser) {//如果当前状态是暂停,并且是由用户手动暂停的，则不处理

                } else if (state == MediaPlayerState.PLAYBACK_COMPLETED) {//视频播放完成
                    safetySeekTo(0);
                    start();
                } else if (state == MediaPlayerState.ERROR) {
                    reset();
                    setAndPrepareDataSource(videoInfo);
                } else {
                    start();
                }
            } else {
                if (getState() != MediaPlayerState.IDLE) {
                    reset();
                }
                setAndPrepareDataSource(videoInfo);
            }
        } else {//播放不同的视频
            if (getState() != MediaPlayerState.IDLE) {
                reset();
            }
            setAndPrepareDataSource(videoInfo);
        }
        if (!TextUtils.isEmpty(videoInfo.getTitle())) {
            mControllerView.setTitle(videoInfo.getTitle());
        }
        setPlaySilence(videoInfo.isPlaySilence());
    }

    public void setPlaySilence(boolean playSilence) {
        if (sShouldMute && playSilence) {
            mute();
            mControllerView.setShouldShowVoiceAnimationOnPlaying(true);
        } else {
            mControllerView.setShouldShowVoiceAnimationOnPlaying(false);
            resetToSystemVolume();
            if (isPrepared()) {
                mMediaPlayer.attachAuxEffect(AudioEffect.CONTENT_TYPE_MUSIC);
            }
        }
    }

    private void mute() {
        if (!mIsMute) {
            mMediaPlayer.setVolume(0.0f, 0.0f);
            mIsMute = true;
        }
    }

    public void resetToSystemVolume() {
        if (mIsMute) {
            mMediaPlayer.setVolume(1.0f, 1.0f);
            mIsMute = false;
        }
    }

    public boolean isMute() {
        return mIsMute;
    }

    public void setShouldMute(boolean shouldMute) {
        sShouldMute = shouldMute;
    }

    public void start() {
//        mTextureView.setKeepScreenOn(true);
        mMediaPlayer.start();
        MediaPlayerUtils.muteAudioFocus(mContext.getApplicationContext(), true);
        if (mIsOrientationListenerEnabled) {
            enableOrientationListener(true);
        }
    }

    public void safetySeekTo(int position) {
        mMediaPlayer.seekTo(position);
    }

    public void pause(boolean isPausedByUser) {
        if (!isPrepared() || isError()) {
            reset();
        } else if (isPlaying()) {
            this.isPausedByUser = isPausedByUser;
            mMediaPlayer.pause();
        }
//        mTextureView.setKeepScreenOn(false);
        tryInsertShortVideoPlayRecord();
    }

    public void rePlay() {
        if (!NetworkHelper.isNetworkAvailable(mContext)) {
            //XLToast.showCenterToast(mContext, XLToast.XLToastType.XLTOAST_TYPE_ALARM, "无网络连接");
            return;
        }
        if (mPlayInfo == null || TextUtils.isEmpty(mPlayInfo.getVideoInfo().getSourceUrl()) || getState() == MediaPlayerState.RELEASE) {
            return;
        }
        limitDownloadSpeed();
        safetySeekTo(0);

        //重播
        if (getState() == MediaPlayerState.PLAYBACK_COMPLETED) {
            if (mPlayInfo != null) {
                MLog.debug("liu.js.media", "onVideoPlayStart");
                VideoInfo videoInfo = mPlayInfo.getVideoInfo();
                if (videoInfo.getPlayListener() != null) {
                    videoInfo.getPlayListener().onVideoPlayStart(videoInfo);
                }
            }
        }
        play(mPlayInfo.getVideoInfo());
    }

    private void limitDownloadSpeed() {
//        boolean shouldLimit = SpeedLimitHelper.instance().isLimitDownloadSpeed();
//        if (shouldLimit) {
//            hasLimitDownloadSpeed = true;
//        }
//        SpeedLimitHelper.instance().limitDownloadSpeed(shouldLimit);
    }

    private void setAndPrepareDataSource(VideoInfo videoInfo) {
        mSetDataSourceTime = SystemClock.elapsedRealtime();
        mPlaySessionId = System.currentTimeMillis();
        mMediaPlayer.setDataSourceAndPrepare(videoInfo.getSourceUrl());
    }

    public boolean checkIsOnScreen() {
        if (mMediaPlayer == null) {
            return false;
        }
        Rect rect = new Rect();
//        mContainer.getLocalVisibleRect(rect);
//        AutoPlayUtil.getVisibilityPercents(mContext, rect, mContainer);
//        int visibleHeight = rect.height();
        if (AutoPlayUtil.getVisibilityPercents(mContext, rect, mContainer) == 0) {
            return false;
        }
        return true;
    }

    public void stop() {
        if (isPrepared() && getState() != MediaPlayerState.ERROR) {
            if (getState() != MediaPlayerState.STOPPED) {
                mMediaPlayer.stop();
                onPlayEnd(false);
            }
        }
//        mTextureView.setKeepScreenOn(false);
    }

    public MediaPlayerState getState() {
        return mMediaPlayer.getState();
    }

    public int getId() {
        return mPlayerId;
    }

    public int getDuration() {
        if (mPlayInfo == null) {
            return 0;
        }
        //解决某些情况下duration一直为0的问题
        if (mPlayInfo.getDuration() <= 0) {
            mPlayInfo.setDuration(mMediaPlayer.getDuration());
        }
        return mPlayInfo.getDuration();
    }

    public int getCurrentPosition() {
        return mMediaPlayer.getCurrentPosition();
    }

    public View getContainer() {
        return mContainer;
    }

    public boolean isPrepared() {
        return mMediaPlayer.isPrepared();
    }

    private boolean isError() {
        return getState() == MediaPlayerState.ERROR;
    }

    public boolean isFullScreenMode() {
        return isFullScreenMode;
    }

    private void enterFullScreenMode() {
        if (isFullScreenMode) {
            return;
        }
        isFullScreenMode = true;
        mFullScreenChangeTime = SystemClock.elapsedRealtime();
        mGestureView.setShouldDetectorGestureMove(true);
        boolean isVideoHorizontal = isVideoHorizontal() || !mClickLandscape;
        Activity activity = getActivity();
        if (activity != null) {
            hideNavigation();
            if (isVideoHorizontal) {
                isScreenLandscape = true;
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            }
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            if (shouldDetachOnFullScreenMode) {
                removeSelfContainer();
                FrameLayout decorView = (FrameLayout) activity.getWindow().getDecorView();
                addContainerTo(decorView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            }
        }
        resetToSystemVolume();
        mControllerView.onEnterFullScreen();
        if (mediaPlayerFullScreenListener != null) {
            mediaPlayerFullScreenListener.onEnterFullScreen(isVideoHorizontal);
        }
    }

    private void outFullScreenMode() {
        if (!isFullScreenMode) {
            return;
        }
        isFullScreenMode = false;
        mPortraitVideoFullScreen = false;
        mFullScreenChangeTime = SystemClock.elapsedRealtime();
        mGestureView.resetStateToIdle();
        mGestureView.setShouldDetectorGestureMove(false);
        Activity activity = getActivity();
        if (activity != null) {
            isScreenLandscape = false;
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            showNavigation();
            if (shouldDetachOnFullScreenMode) {
                ViewGroup prevParent = mPrevParent;
                ViewGroup.LayoutParams prevParams = mPrevParams;
                if (prevParent != null) {
                    removeSelfContainer();
                    addContainerTo(prevParent, prevParams.width, prevParams.height);
                }
            }
        }
        mControllerView.onOutFullScreen();
        if (mediaPlayerFullScreenListener != null) {
            mediaPlayerFullScreenListener.onOutFullScreen(isVideoHorizontal());
        }
    }

    private void hideNavigation() {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        int uiOptions = activity.getWindow().getDecorView().getSystemUiVisibility();
        int newUiOptions = uiOptions;
        if (Build.VERSION.SDK_INT >= 14) {
            newUiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        }
        if (Build.VERSION.SDK_INT >= 16) {
            newUiOptions |= View.SYSTEM_UI_FLAG_FULLSCREEN;
        }
        if (Build.VERSION.SDK_INT >= 19) {
            newUiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        }
        activity.getWindow().getDecorView().setSystemUiVisibility(newUiOptions); //4102 0   4016 6
    }

    private void showNavigation() {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        int uiOptions = activity.getWindow().getDecorView().getSystemUiVisibility();
        int newUiOptions = uiOptions;
        if (Build.VERSION.SDK_INT >= 14) {
            newUiOptions &= (~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
        if (Build.VERSION.SDK_INT >= 16) {
            newUiOptions &= (~View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
        if (Build.VERSION.SDK_INT >= 19) {
            newUiOptions &= (~View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        activity.getWindow().getDecorView().setSystemUiVisibility(newUiOptions); //4102 0   4016 6
    }


    /**
     * 全屏切换后的一秒内定为全屏切换中状态，用来规避由于全屏切换，导致列表滚动，进而导致视频播放异常停止问题
     *
     * @return
     */
    public boolean isFullScreenChanging() {
        return SystemClock.elapsedRealtime() - mFullScreenChangeTime < 1000;
    }

    void toggleFullScreenMode() {
        if (isFullScreenMode) {
            onOutFullScreenClick();
        } else {
            onEnterFullScreenClick();
        }
    }

    private void onEnterFullScreenClick() {
        mPortraitVideoFullScreen = !isVideoHorizontal();
        mClickPortrait = false;
        mClickLandscape = true;
        enterFullScreenMode();
    }

    void onOutFullScreenClick() {
        enableOrientationListener(true);
        mClickPortrait = true;
        mClickLandscape = false;
        outFullScreenMode();
    }

    /**
     * 将播放器从View节点移除
     */
    public void removeSelfContainer() {
        MLog.debug(TAG,"removeSelfContainer--");
        if (mContainer != null && mContainer.getParent() != null) {
            mPrevParent = (ViewGroup) mContainer.getParent();
            mPrevParams = mContainer.getLayoutParams();
            mPrevParent.removeView(mContainer);
        }
    }

    /**
     * 将播放器界面添加到指定的ViewGroup上
     *
     * @param parent
     * @param width
     * @param height
     */
    public void addContainerTo(ViewGroup parent, int width, int height) {
        MLog.debug(TAG,"addContainerTo--parent=" + parent);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, height);
        parent.addView(mContainer, params);
    }

    public void addContainerTo(ViewGroup parent) {
        addContainerTo(parent, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    public boolean isVideoHorizontal() {
        return mVideoWidth >= mVideoHeight;
    }

    /**
     * 添加视频播放全屏状态切换监听
     *
     * @param listener
     */
    public void setMediaPlayerFullScreenListener(MediaPlayerFullScreenListener listener) {
        this.mediaPlayerFullScreenListener = listener;
    }

    private Activity getActivity() {
        if (mContext != null && mContext instanceof Activity) {
            return (Activity) mContext;
        }
        return null;
    }

    public void setContext(Context context) {
        this.mContext = context;
    }

    /**
     * 返回键处理
     *
     * @return true，表示处理掉返回键，不再往下传递
     */
    public boolean handleBackPress() {
        if (isFullScreenMode) {
            onOutFullScreenClick();
            return true;
        }
        return false;
    }

    /**
     * 视频播放完成监听
     *
     * @param onCompletionListener
     */
    public void setOnCompletionListener(MediaPlayer.OnCompletionListener onCompletionListener) {
        this.onCompletionListener = onCompletionListener;
    }

    /**
     * 设置播放完成后是否显示播放完成界面，默认显示
     */
    public void setCompletionViewEnable(boolean isEnable) {
        if (isEnable) {
            mMediaPlayer.addStateChangeListener(mCompletionView);
        } else {
            mMediaPlayer.removeStateChangeListener(mCompletionView);
            mCompletionView.setVisibility(View.GONE);
        }
    }

    public String getTag() {
        return mTag;
    }

    public void setTag(String tag) {
        this.mTag = tag;
    }

    void onNetworkChange() {
        if (!NetworkHelper.isNetworkAvailable(mContext)) {
            return;
        }
        boolean isCanPlay = true;
        if (NetworkHelper.isActiveNetworkMobile(mContext)) {
            String movieId = "";
            if (mPlayInfo != null && mPlayInfo.getVideoInfo() != null) {
                movieId = mPlayInfo.getVideoInfo().getMovieId();
            }
            isCanPlay = MediaPlayerManager.getInstance().checkCanPlayAndPromptOnMobileNetwork(movieId, mContext, new MediaPlayerUtils.OnCheckNetworkDialogListener() {
                @Override
                public void onLeftBtnClick() {

                }

                @Override
                public void onRightBtnClick() {
                    if (mPlayInfo != null) {
                        doPlay(mPlayInfo.getVideoInfo(), mPlayInfo);
                    }
                }

                @Override
                public void onBackKeyDown() {

                }
            });
        }
        if (!isCanPlay) {
            stop();
            reset();
        }
    }

    /**
     * 小屏播放时，是否显示title
     *
     * @param isVisiable
     */
    public void setTitleVisiableInSmallScreen(boolean isVisiable) {
        mControllerView.setTitleVisiableInSmallScreen(isVisiable);
    }

    public void setControllerVisiableListener(MediaPlayerControllerView.OnControllerVisiableListener listener) {
        mControllerView.setVisiableListener(listener);
    }

    /**
     * 设置全屏时，是否需要将界面从当前View树上移除
     *
     * @param shouldDetachOnFullScreen
     */
    public void setShouldDetachOnFullScreenMode(boolean shouldDetachOnFullScreen) {
        this.shouldDetachOnFullScreenMode = shouldDetachOnFullScreen;
    }

    public boolean isPlaying() {
        return getState() == MediaPlayerState.STARTED || getState() == MediaPlayerState.LOADING;
    }

    public boolean isPaused(){
        return getState() == MediaPlayerState.PAUSED;
    }

    public int getVideoWidth() {
        return mVideoWidth;
    }

    public int getVideoHeight() {
        return mVideoHeight;
    }

    public long getPlaySessionId() {
        return mPlaySessionId;
    }

    /**
     * 设置上一集按钮的隐藏、显示
     *
     * @param isVisiable
     */
    public void setPrevPlayBtnVisiable(boolean isVisiable) {
        mControllerView.setPrevPlayBtnVisiable(isVisiable);
        mCompletionView.setPrevPlayBtnVisiable(isVisiable);
    }

    /**
     * 设置下一集按钮的隐藏、显示
     *
     * @param isVisiable
     */
    public void setNextPlayBtnVisiable(boolean isVisiable) {
        mControllerView.setNextPlayBtnVisiable(isVisiable);
        mCompletionView.setNextPlayBtnVisiable(isVisiable);
    }

    /**
     * 设置是否应该播放下一集视频
     * 用于控制全屏时的切换
     *
     * @param isEnable
     */
    public void setAutoPlayNextEnable(boolean isEnable) {
        mAutoPlayEnable = isEnable;
    }

    public VideoInfo getVideoInfo() {
        if (mPlayInfo == null) {
            return null;
        }
        return mPlayInfo.getVideoInfo();
    }

    public void setOnControllerClickListener(OnControllerClickListener listener) {
        mControllerView.setOnControllerClickListener(listener);
        mCompletionView.setOnControllerClickListener(listener);
    }

    public void setClickToDetailMode(MediaPlayerGestureView.OnClickToDetailListener listener) {
        mGestureView.setClickToDetailListener(listener);
    }

    public void tryInsertShortVideoPlayRecord() {
        if (mPlayInfo == null || !mPlayInfo.getVideoInfo().isShouldInsertRecord() || mPlayInfo.getCurrentPlayPosition() < 3000) {
            return;
        }
        VideoInfo videoInfo = mPlayInfo.getVideoInfo();
//        FeedDataUtils.insertShortVideoPlayRecord(getCurrentPosition(), mPlayInfo.getDuration(),
//                videoInfo.getMovieId(),
//                videoInfo.getGcid(),
//                videoInfo.getTitle(),
//                videoInfo.getSourceUrl()); // 短视频播放记录
//        mPlayInfo.setHasInsertPlayRecord(true);
    }

    MediaPlayerControllerView getControllerView() {
        return mControllerView;
    }

    public void setShowControllerOnIdle(boolean isShowControllerOnIdle) {
        mControllerView.setShowControllerOnIdle(isShowControllerOnIdle);
    }

    public void setControllerViewType(int type) {
        mViewType = type;
        mControllerView.setViewType(type);
    }

    public int getViewType() {
        return mViewType;
    }

    public void addStateChangeListener(MediaPlayerStateChangeListener listener) {
        mMediaPlayer.addStateChangeListener(listener);
    }

    public void removeStateChangeListener(MediaPlayerStateChangeListener listener) {
        mMediaPlayer.removeStateChangeListener(listener);
    }

    @Override
    public String toString() {
        String movieId = null;
        if (getVideoInfo() != null) {
            movieId = getVideoInfo().getMovieId();
        }
        return "id=" + mPlayerId + "|tag=" + mTag + "|movieId=" + movieId;
    }

    /**
     * 设置是否需要显示LoadingView的黑色背景，用来遮盖两个视频切换播放时，上一个视频残留的图像，默认值为false
     *
     * @param shouldShowLoadingBackground
     */
    public void setShouldShowLoadingBackground(boolean shouldShowLoadingBackground) {
        mControllerView.setShouldShowLoadingBackground(shouldShowLoadingBackground);
    }

    /**
     * 设置播放完成页面重播按钮点击监听，如果设置了该监听，则不再执行播放器的replay操作，否则默认执行replay操作
     *
     * @param listener
     */
    public void setCompletionReplayListener(View.OnClickListener listener) {
        mCompletionView.setReplayClickListener(listener);
    }

    public void setCompletionViewOnClickListener(View.OnClickListener listener) {
        mCompletionView.setOnClickListener(listener);
    }

    public int getListPosition() {
        return mListPosition;
    }

    public void setListPosition(int listPosition) {
        mListPosition = listPosition;
    }

    public void resetListenersAndParams() {
        setAutoPlayNextEnable(false);
        setClickToDetailMode(null);
        setCompletionReplayListener(null);
        setCompletionViewEnable(true);
        setCompletionViewOnClickListener(null);
        setControllerVisiableListener(null);
        setListPosition(0);
        setMediaPlayerFullScreenListener(null);
        setNextPlayBtnVisiable(false);
        setOnCompletionListener(null);
        setOnControllerClickListener(null);
        setOrientationListenerEnabled(false);
        setPrevPlayBtnVisiable(false);
        setShouldDetachOnFullScreenMode(true);
        setShouldShowLoadingBackground(false);
        setShowControllerOnIdle(false);
        setTitleVisiableInSmallScreen(true);
    }
}
